package com.cyt.sys.service.impl;

import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.dao.SysRuleDao;
import com.cyt.sys.model.po.SysDictContent;
import com.cyt.sys.model.po.SysRule;
import com.cyt.sys.model.vo.SysRuleVo;
import com.cyt.sys.service.SysRuleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 数据权限service实现类
 *
 * @author shengQiang yu
 * @date 2019-03-22 10:04
 */
@Service("baseRuleService")
public class SysRuleServiceImpl extends BaseServiceImpl<SysRule> implements SysRuleService {
    @Resource
    private SysRuleDao sysRuleDao;

    @Autowired
    public void setBaseDao(SysRuleDao sysRuleDao) {
        this.baseDao = sysRuleDao;
    }

    /**
     *
     * @param sysRuleVo 对象
     * @param pageSize 当前页面
     * @param pageNum 每页数据量
     * @return
     * @author shengQiang yu
     * @date 2019-03-22 10:08
     */
    public ReturnResult page(SysRuleVo sysRuleVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" sort desc,create_time desc");
        List<SysRule> list=listExample(sysRuleVo);
        PageInfo<SysRule> page=new PageInfo<SysRule>(list);
        return new ReturnResult(page.getList(),page.getTotal(),page.isHasNextPage());
    }
    /**
     * 根据id删除
     *
     * @param id 主键id
     * @return
     * @author shengQiang yu
     * @date 2019-03-22 10:07
     */
    public ReturnResult delete(String id) {
        int num= sysRuleDao.deleteByPrimaryKey(id);
        if(num>0){
            return new ReturnResult();
        }else{
            return new ReturnResult(ErrorCode.CODE_101,ErrorCode.CODE_101_MSG);
        }

    }
    /**
     * 获取对象集合
     *
     * @param sysRuleVo 对象
     * @return
     * @author shengQiang yu
     * @date 2019-03-22 10:06
     */
    public ReturnResult list(SysRuleVo sysRuleVo) {
        List<SysRule> list = listExample(sysRuleVo);
        return new ReturnResult(list);
    }
    /**
     * 添加或修改
     *
     * @param sysRuleVo 对象
     * @return
     * @author shengQiang yu
     * @date 2019-03-22 10:07
     */
    @Override
    public ReturnResult addOrUpdate(SysRuleVo sysRuleVo) {
        if (sysRuleVo.getId() == null || "".equals(sysRuleVo.getId())) {
            SysRule sysRule = new SysRule();
            sysRule.setId(BaseUtil.uId());
            sysRule.setName(sysRuleVo.getName());
            sysRule.setType(sysRuleVo.getType());
            /**
             * 获取菜单的级别和code
             */
            if (StringUtils.isEmpty(sysRuleVo.getParentId())) {
                sysRule.setGrade(BaseConstant.GRADE_ONE);
                String code= sysRuleDao.AcceptMaxCode(new SysRuleVo(sysRule.getGrade()));
                if(StringUtil.isEmpty(code)){
                    sysRule.setCode(BaseConstant.MENU_CODE_MIN);
                }else{
                    sysRule.setCode(Long.parseLong(code)+1+"");
                }
            } else {
                SysRule parentRule = selectByPrimaryKey(sysRuleVo.getParentId());
                sysRule.setGrade(parentRule.getGrade()+1);
                String code= sysRuleDao.AcceptMaxCode(new SysRuleVo(sysRule.getGrade(), sysRuleVo.getParentId()));
                if(StringUtil.isEmpty(code)){
                    sysRule.setCode(parentRule.getCode()+ BaseConstant.MENU_CODE_MIN);
                }else{
                    sysRule.setCode(Long.parseLong(code)+1+"");
                }
            }
            sysRule.setSqlContent(sysRuleVo.getSqlContent());
            sysRule.setPermission(sysRuleVo.getPermission());
            sysRule.setParentId(sysRuleVo.getParentId());
            sysRule.setSort(sysRuleVo.getSort());
            sysRule.setCreateTime(new Date());
            int num = sysRuleDao.insert(sysRule);
            if (num <= 0) {
                return new ReturnResult(BaseConstant.DATABASE_ERROR_INSERT);
            }
        } else {
            if(DictCode.RULE_TYPE_RULE.equalsIgnoreCase(sysRuleVo.getType())){
                //规则类型，需要判断下面是否子类，如果有不能修改为规则
                String code= sysRuleDao.AcceptMaxCode(new SysRuleVo(0, sysRuleVo.getId()));
                if(StringUtil.isNotEmpty(code)){
                    //存在子类
                    return new ReturnResult(ErrorCode.CODE_10, sysRuleVo.getName()+BaseConstant.BASE_UPDATE_RULE_ERROR);
                }
            }else {
                sysRuleVo.setSqlContent("");
                sysRuleVo.setPermission("");
            }
            SysRule sysRule = sysRuleDao.selectByPrimaryKey(sysRuleVo.getId());
            sysRule.setName(sysRuleVo.getName());
            sysRule.setType(sysRuleVo.getType());
            sysRule.setPermission(sysRuleVo.getPermission());
            sysRule.setSqlContent(sysRuleVo.getSqlContent());
            sysRule.setSort(sysRuleVo.getSort());
            int num = sysRuleDao.updateByPrimaryKey(sysRule);
            if (num <= 0) {
                return new ReturnResult(BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_MSG);
    }


    /**
     * 获取数据权限树
     *
     * @param sysRuleVo vo对象
     * @return
     * @author shengQiang yu
     * @date 2019-03-22 14:57
     */
    @Override
    public ReturnResult dTreeList(SysRuleVo sysRuleVo) {
        List<SysRule> list = listExample(sysRuleVo);
        List<Map<String,Object>> dtreeEntityList=new ArrayList<Map<String,Object>>();
        for(SysRule sysRule :list){
            Map<String,Object> dtreeEntity=new HashedMap();
            dtreeEntity.put("id", sysRule.getId());
            dtreeEntity.put("title", sysRule.getName());
            dtreeEntity.put("type", sysRule.getType());
            dtreeEntity.put("parentId", StringUtils.isEmpty(sysRule.getParentId())? "0": sysRule.getParentId());
            dtreeEntity.put("isLast",isLast(list, sysRule.getId()));
            Map<String,String> m=new HashedMap();
            m.put("type","0");
            m.put("isChecked","0");
            List<Map<String,String>> dtreeCheckEntityList=new ArrayList<Map<String,String>>();
            dtreeCheckEntityList.add(m);
            dtreeEntity.put("checkArr",dtreeCheckEntityList);
            dtreeEntityList.add(dtreeEntity);
        }
        return new ReturnResult(dtreeEntityList);
    }

    /**
     * 获取下拉框数据
     *
     * @param sysRuleVo vo对象
     * @param dictType 字典码标识
     * @return
     * @author shengQiang yu
     * @date 2019-03-22 14:57
     */
    @Override
    public ReturnResult selectData(SysRuleVo sysRuleVo, String dictType) {
        List<SysRule> list = listExample(sysRuleVo);
        List<SysDictContent> sysDictContentList =new ArrayList<>();
        for(SysRule sysRule :list){
            SysDictContent sysDictContent =new SysDictContent();
            sysDictContent.setId(sysRule.getId());
            sysDictContent.setName(sysRule.getName());
            sysDictContent.setStatus(DictCode.BASE_STATUS_NORMAL);
            sysDictContent.setDictType(dictType);
            sysDictContent.setValue(sysRule.getId());
            sysDictContent.setCreateTime(sysRule.getCreateTime());
            sysDictContentList.add(sysDictContent);
        }
        return new ReturnResult(sysDictContentList);
    }
    /**
     * 获取对象集合
     *
     * @param sysRuleVo 对象
     * @return
     * @author shengQiang yu
     * @date 2019-03-22 10:06
     */
    public List<SysRule> listExample(SysRuleVo sysRuleVo) {
        Example example = new Example(SysRule.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause(" sort desc,create_time desc");
        if(StringUtil.isNotEmpty(sysRuleVo.getName())){
            criteria.andLike("name","%"+ sysRuleVo.getName()+"%");
        }
        if(StringUtil.isNotEmpty(sysRuleVo.getCode())){
            criteria.andLike("code","%"+ sysRuleVo.getCode()+"%");
        }
        if(StringUtil.isNotEmpty(sysRuleVo.getType())){
            criteria.andEqualTo("type", sysRuleVo.getType());
        }
        List<SysRule> list= sysRuleDao.selectByExample(example);
        return list;
    }

    /**
     *@Author: YuShengQiang
     *@Date: 2018-12-05 17:44
     *@Description:判断当时对象是否有子对象
     */
    private boolean isLast(List<SysRule> list, String id){
        if(list!=null&&list.size()>0&&StringUtil.isNotEmpty(id)){
            for(SysRule sysRule :list){
                if(id.equals(sysRule.getParentId())){
                    return false;
                }
            }
        }
        return true;
    }
}
